//
//  AddFriendlyLinkViewController.m
//  YinHang
//
//  Created by idea on 14-9-18.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "AddFriendlyLinkViewController.h"

@interface AddFriendlyLinkViewController ()<ASIHTTPRequestDelegate>{
    MBProgressHUD *postHud;
    
    /* 提交发布信息请求 */
    ASIFormDataRequest *postInfoRequest;
    /* 获取link */
    ASIFormDataRequest *getLink;
    
    //参数
    NSString *action;
    NSDictionary *paramsDict;

}

@end

@implementation AddFriendlyLinkViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = _navTitle;
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    _isAdd = YES;//添加或者修改 默认添加 
    [self addOrAlter];//添加或修改

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Custom Method
//收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self AllresignFirstResponder];
}
-(void)AllresignFirstResponder{
    [_webName resignFirstResponder];
    [_webURL resignFirstResponder];
}
//提交
- (IBAction)commit:(id)sender {
    [self AllresignFirstResponder];
    //检查输入为空
    if ([NSString emptyValidate:_webName.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入网址名称"];
        return;
    }
    if ([NSString emptyValidate:_webURL.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入网址"];
        return;
    }
    //action = @"friendlyLink";
    
    [self postInformation];//提交到服务器
    
    
   
}
-(void)back{
    [postInfoRequest cancel];
    [getLink cancel];
    [self.navigationController popViewControllerAnimated:YES];
}
/* 提交发布信息请求 */
- (void)postInformation {
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if(_isAdd){
            action = @"linksadd";
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postInfoRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postInfoRequest.requestMethod = @"POST";
        // 设置超时时间
        postInfoRequest.timeOutSeconds = 60;
        postInfoRequest.delegate = self;
        // 设置参数
        paramsDict = @{@"uid":UNAME,@"kname":_webName.text,@"kweb":_webURL.text};//uid会员名;kname:网址名称;kweb:网址
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postInfoRequest.postBody = [paramsData mutableCopy];
        
        [postInfoRequest startAsynchronous];
        }
        else{
            action = @"linksupdate";
            if (!postHud || postHud.hidden == YES) {
                // 提示正在加载数据...
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在发布，请稍后...";
            }
            
            postInfoRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
            postInfoRequest.requestMethod = @"POST";
            // 设置超时时间
            postInfoRequest.timeOutSeconds = 60;
            postInfoRequest.delegate = self;
            // 设置参数
            paramsDict = @{@"kid":_linkId,@"uid":UNAME,@"kname":_webName.text,@"kweb":_webURL.text};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            postInfoRequest.postBody = [paramsData mutableCopy];
            
            [postInfoRequest startAsynchronous];
            
        }
    }
}
//修改还是添加
-(void)addOrAlter{
    if ([_navTitle isEqualToString:@"添加链接"]) {
        
    }else{
        _isAdd = NO;
        _webName.text = _webName_;
        _webURL.text = _webURL_;
    }
}

#pragma mark - ASIHttpRequestDelegate method
- (void)requestFinished:(ASIHTTPRequest *)request {
    
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    NSLog(@"%@",result);
    // 1. 是否解析有错误
    if (!err) {
    
    // 2. 判断错误码
    NSInteger errorCode = [result[@"errorCode"]integerValue];
    if (errorCode == 0) {
        [postHud hide:YES];
        
        
        // 提示发布成功
        [UIView animateWithDuration:0 animations:^{
            if (_isAdd) {
                [SVProgressHUD showSuccessWithStatus:@"添加成功！"];
                 [self.navigationController popViewControllerAnimated:YES];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"修改成功！"];
                 [self.navigationController popViewControllerAnimated:YES];
            }
    
            
        } completion:^(BOOL finished) {
            
        }];
    } else {
        [postHud hide:YES];
        [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
    }
    } else {
    [postHud hide:YES];
    [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request {
    
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

-(void)dealloc{
    [postInfoRequest cancel];
    [getLink cancel];
}

@end
